<template>
	<view class="no-list" v-if="is_init">

	</view>
	<!-- <view class="no-list" v-else-if="!is_login" @click="toLogin()">
		- 去登录 -
	</view> -->
	<view class="no-list" v-else-if="!has_quan">
		暂无权限
	</view>
	<!-- <view class="no-list" v-else-if="!is_open">
		已关店
	</view> -->
	<view class="ys" v-else>
		<view class="chatlist" :style="{paddingBottom:boxExtraStyle}">
			<view class="chatscroll" :style="{paddingBottom:scrollHeight}">
				<view class="chatlength">
					<view class="more_text" v-show="allow_refresh">下拉加载更多</view>
					<view :class="item.say_type == 1?'chatitem mychat':'chatitem '" v-for="(item,index) in chatList"
						:key="index" :id="'tab'+item.id">
						<image class="headerimg" :src="item.head_url || '/static/index/head.png'" mode=""></image>
						<view class="item-info">
							<view class="name">
								{{item.name}} <text>{{item.create_time}}</text>
							</view>
							<view class="item-msg" v-if="item.type == 1">
								<text>{{item.content}}</text>
							</view>
							<view class="item-imgbox" v-else-if="item.type == 2">
								<image :src="item.path" mode="heightFix" @click="bigImg(item.path)">
								</image>
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>
		<view class="sendmsg" v-if="allow_send">
			<view class="top">
				<view class="imgbox emo">
					<image @click="openEx" src="/static/bq.png" mode="widthFix"></image>
				</view>
				<view class="textbox">
					<textarea v-model="content" maxlength="-1" :style="minHeight" @linechange="changeLine"
						@input="changeInput" @focus="closeEx" :show-confirm-bar="false" auto-height></textarea>
					<view class="" id="hiddenText"
						style="width: 100%; white-space: pre-wrap;word-wrap: break-word;visibility: hidden;line-height: 24px;">
						{{content}}
					</view>
				</view>

				<view class="imgbox" v-if="allow_upload_img">
					<image v-if="content == ''" @click="uploadImg" src="/static/add.png" mode="widthFix"></image>
				</view>
				<text v-if="!allow_upload_img" @click="confirmSend">发送</text>
				<text v-else-if="content != ''" @click="confirmSend">发送</text>
			</view>
			<view class="emoji">
				<emoKeyboard :show="show_ex" :data="EmojiData" @change="change" @delMsg="delMsg"></emoKeyboard>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		getUserRoom
	} from "@/api/user.js"
	import {
		UserInfo
	} from "@/api/api.js"
	import {
		getRoomDetail,
		getChat,
		sendMsg,
		updateUnread
	} from "@/api/chat.js"
	import emoKeyboard from '@/components/emoji/emoKeyboard.vue';
	export default {
		data() {
			return {
				is_init: true,
				websocket_url: '',
				room_id: '',
				area_id: '',
				store_id: '',
				content: '',
				chatList: [],
				temp_list: [],
				page: 1,
				total_page: 1,
				last_new_id: '',
				img_url: '',
				img_url_show: '',
				scrollView: 'tab',
				user_id: '',
				triggered: false,
				_freshing: false,
				allow_refresh: true,
				is_init: true,
				allow_send: false, //是否允许发送消息
				last_id: '',
				// #ifdef H5
				minHeight: "min-height:auto",
				// #endif
				// #ifndef H5
				minHeight: 'min-height:40px',
				// #endif
				show_ex: false,
				//表情可以去这里复制https://geekerline.com/emoji/
				EmojiData: [
					"😀", "😃", "😄", "😁", "😆", "😅", "😂", "🤣", "😊", "😇", "🙂", "🙃", "😉", "😌", "😍", "🥰",
					"😘", "😗", "😙", "😚", "😋", "😛", "😝", "😜", "🤪", "🤨", "🧐", "🤓", "😎", "🤩", "🥳", "😏",
					"😒", "😞", "😔", "😟", "😕", "🙁", "😣", "😖", "😫", "😩", "🥺", "😢", "😭", "😤", "😠", "😡",
					"🤬", "🤯", "😳", "🥵", "🥶", "😱", "😨", "😰", "😥", "😓", "🤗", "🤔", "🤭", "🤫", "🤥", "😶",
					"😐", "😑", "😬", "🙄", "😯", "😦", "😧", "😮", "😲", "😴", "🤤", "😪", "😵", "🤐", "🥴", "🤢",
					"🤮", "🤧", "😷", "🤒", "🤕", "🤑", "🤠", "😈", "👿", "👹", "👺", "🤡", "💩", "👻", "💀", "☠",
					"👽", "👾", "🤖", "🎃", "😺", "😸", "😹", "😻", "😼", "😽", "🙀", "😿", "😾"
				],
				is_connect: false,
				fail_count: 0,
				is_login: false,
				has_quan: false,
				is_open: false,
				user_id: '',
				scrollHeight: '',
				allow_upload_img: false,
				chatLastMsgId: '',
				confirm_text: '',
				boxExtraStyle: ''
			}
		},
		components: {
			emoKeyboard
		},
		onUnload() {
			this.is_connect && uni.closeSocket({
				success(data) {
					console.log('WebSocket 关闭成功！');
				}
			})
		},
		onNavigationBarButtonTap(e) {
			uni.navigateTo({
				url: '/shoper/user/chat/list?room_id=' + this.room_id
			})
		},
		async onLoad(e) {
			if (!e.room_id && !e.area_id) {
				uni.navigateBack()
			}
			this.room_id = e.room_id
			this.area_id = e.area_id
			let that = this
			let reqRes = await UserInfo()
			this.is_init = false
			let reqData = reqRes.data
			if (!reqData.user) {
				this.is_login = false
				// return false
				this.user_id = this.generateUUID()
				console.log(this.user_id);
			} else {
				this.is_login = true
				this.user_id = reqData.user_id
			}
			// if (!reqData.is_store) {
			// 	this.has_quan = false
			// 	return false
			// }
			// this.has_quan = true
			// if (!reqData.is_open) {
			// 	this.is_open = false
			// 	return false
			// }
			// this.is_open = true

			this.allow_upload_img = reqData.allow_upload_img
			this.websocket_url = reqData.websocket
			// let info = await getUserRoom()
			// if (info.code == 0) {
			// 	this.room_id = info.data.room.id
			// 	this.store_id = info.data.store_id
			// 	this.websocket_url = info.data.websocket
			// 	uni.setNavigationBarTitle({
			// 		title: info.data.room.name
			// 	})
			// } else if (info.code == 500) {
			// 	uni.$showMsg(info.msg, function() {
			// 		uni.switchTab({
			// 			url: '/pages/user/index'
			// 		})
			// 	})
			// } else {
			// 	uni.redirectTo({
			// 		url: '/shoper/user/chat/choose-area'
			// 	})
			// 	return false
			// }
			//聊天记录
			//清空未读消息
			this.getRoomDetail()
			this.getChat()
			// this.updateUnread()
			uni.closeSocket({
				success: () => {

				},
				fail: (err) => {
					console.log(err);
				}
			})
			if (!this.is_connect) {
				that.webSocket()
			}
			// uni.closeSocket({
			// 	success: (data) => {
			// 		that.webSocket()
			// 	},
			// 	fail(err) {
			// 		that.webSocket()
			// 	}
			// })


		},
		// onLoad(options) {

		// },
		onPageScroll(e) {
			if (e.scrollTop < 5) {
				if (!this.allow_refresh) {
					// uni.stopPullDownRefresh()
					// uni.$showMsg('没有更多了')
					return false
				}
				this.onrefresh()
			}
		},
		// onPullDownRefresh() {

		// },
		methods: {
			webSocket() {
				var that = this
				console.log('连接', this.is_connect);
				if (this.is_connect) {
					return false
				}
				// uni.showLoading({
				// 	title: '连接房间。。。'
				// })
				this.socketTask = uni.connectSocket({
					// url: 'wss://www.example.com/socket',
					url: `${that.websocket_url}?room_id=${that.room_id}&user_id=${that.user_id}`,
					success: (res) => {
						console.log('连接成功', res)
					},
					fail: (err) => {
						console.log('链接失败', err);
					}
				});
				this.socketTask.onOpen(function(res) {
					uni.hideLoading()
					console.log('WebSocket连接已打开！');
					that.is_connect = true
				});
				this.socketTask.onError(function(res) {
					that.is_connect = false
					console.log('WebSocket连接打开失败，请检查！');
					that.fail_count++
					if (that.fail_count <= 7) {
						// uni.showLoading({
						// 	title: '重新连接。。。'
						// })
						that.webSocket()
					}

				});
				this.socketTask.onClose(function(res) {
					that.is_connect = false
					console.log('WebSocket 已关闭！');
				});
				this.socketTask.onMessage(function(res) {
					let data = JSON.parse(res.data)
					console.log('收到服务器内容：', data, that.is_connect);
					if (data.type == 'ping') {
						return
					}
					if (data.code == 0) {
						let content = data.content
						if (data.type == 'message') {
							let messageData = content.content
							if (messageData.user_id == that.user_id) {
								messageData.say_type = 1
							} else {
								messageData.say_type = 2
							}
							that.chatList.push(messageData)
							setTimeout(() => {
								that.scrollView = 'tab' + messageData.id
								that.chatLastMsgId = 'tab' + messageData.id
								uni.pageScrollTo({
									selector: `#${that.scrollView}`
								})
								console.log(that.scrollView);

							})
							that.updateUnread()
						}
					} else {
						uni.$showMsg(data.msg || '接收失败')
					}

				});
			},
			toLogin() {
				// #ifdef H5
				uni.navigateTo({
					url: '/pages/login/index'
				})
				// #endif
				// #ifdef MP-WEIXIN
				uni.navigateTo({
					url: '/pages/login/login'
				})
				// #endif
			},
			UserInfo() {
				UserInfo().then(res => {

				})
			},
			getRoomDetail() {
				getRoomDetail({
					room_id: this.room_id,
					area_id: this.area_id
				}).then(res => {
					if (res.code == 0) {
						uni.setNavigationBarTitle({
							title: res.data.name
						})
						this.confirm_text = res.data.confirm_text
						this.allow_send = res.data.allow_send
					} else {
						return uni.$showMsg(res.msg)
					}
				})
			},
			change(emoji) {
				this.content += emoji
			},
			delMsg() { //删除
				if (!this.content) return
				const lastTwoChars = this.content.slice(-2);
				if (this.isEmoji(lastTwoChars)) {
					this.content = this.content.substring(0, this.content.length - 2);
				} else {
					this.content = this.content.substring(0, this.content.length - 1);
				}
			},
			isEmoji(str) {
				// 匹配表情的正则表达式
				const regExp = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g;
				return regExp.test(str);
			},
			//k开关表情
			closeEx() {
				let that = this
				this.show_ex = false
				this.scrollHeight = ''
				if (that.scrollHeight) {
					that.$nextTick(() => {
						that.setPageScrollTo(`#${that.chatLastMsgId}`)
					})
				}
			},
			openEx() {
				let that = this
				this.show_ex = !this.show_ex
				setTimeout(() => {
					let view = uni.createSelectorQuery().in(this).select(".sendmsg");
					view.boundingClientRect((data) => {
						if (that.show_ex) {
							that.scrollHeight = `${data.height}px`
						} else {
							that.scrollHeight = ''
						}
						if (that.scrollHeight) {
							that.$nextTick(() => {
								that.setPageScrollTo(`#${that.chatLastMsgId}`)
							})
						}

					}).exec()
				}, 100)
			},
			//textarea高度
			changeLine(e) {
				console.log('line', e);
				return false
				let height = e.detail.height
				this.boxExtraStyle = `${height}px`
				if (height < 40) {
					// #ifdef H5
					this.minHeight = 'min-height:auto'
					// #endif
					// #ifndef H5
					this.minHeight = 'min-height:40px'
					// #endif
				} else if (height < 80) {
					this.minHeight = 'min-height:' + height + 'px'
				}
			},
			changeInput(e) {
				const value = e.detail.value;
				const lines = value.split('\n').length;
				this.$nextTick(() => {
					this.calculateLineCount(lines)
				})
			},
			calculateLineCount: function(oldLine) {
				let that = this
				const query = wx.createSelectorQuery();
				query.select('#hiddenText').boundingClientRect((rect) => {
					if (rect) {
						const lineHeight = 24; // 设定每行的高度，根据CSS中的line-height调整
						let lineCount = Math.floor(rect.height / lineHeight);
						lineCount = lineCount == 0 ? 1 : lineCount
						lineCount = Math.max(oldLine, lineCount)
						let height = 40 + 24 * (lineCount - 1)
						if (height <= 140) {
							that.minHeight = 'min-height:' + height + 'px'
						}

					}
				}).exec();
			},
			getChat(duration = 300) {
				let that = this
				getChat({
					room_id: that.room_id,
					area_id: that.area_id,
					page: that.page
				}).then(res => {
					if (res.code == 403) {
						this.has_quan = false;
						return false
					}
					if (res.code == 501) {
						uni.redirectTo({
							url: '/pages/user/role'
						})
						return false
					}
					this.has_quan = true
					that._freshing = false;
					that.triggered = false;
					uni.stopPullDownRefresh()
					if (res.code == 0) {

						if (that.page == 1) {
							var last_msg_id = ''
						} else {
							var last_msg_id = that.chatList[0].id
						}
						that.chatList = [...res.data.data, ...that.chatList]
						that.last_page = res.data.last_page
						if (that.page < that.last_page) {
							that.allow_refresh = true
						} else {
							that.allow_refresh = false
						}
						if (that.chatList.length == 0) {
							return
						}
						that.$nextTick(() => {
							if (that.page == 1) {
								that.scrollView = 'tab' + that.chatList[that.chatList.length - 1].id
								that.chatLastMsgId = 'tab' + that.chatList[that.chatList.length - 1].id
							} else {
								that.scrollView = 'tab' + last_msg_id
							}
							that.updateUnread() // 更新已读
							that.setPageScrollTo(`#${that.scrollView}`)
							// uni.pageScrollTo({
							// 	duration: 0,
							// 	selector: ,
							// 	success() {
							// 		console.log('滚动成功');
							// 	},
							// 	fail(err) {
							// 		console.log('滚动失败');
							// 	}
							// })
							if (that.page < res.data.last_page) {
								that.page++
							}
						})
					} else {
						return uni.$showMsg(res.msg)
					}
				})
			},
			setPageScrollTo(selector) {
				let view = uni.createSelectorQuery().in(this).select(selector);
				view.boundingClientRect((res) => {
					console.log('滚动', res);
					uni.pageScrollTo({
						scrollTop: res.top - 30, // -30 为多显示出大半个消息的高度，示意上面还有信息。
						duration: 0
					});
				}).exec();
			},
			async getChatList() {
				let that = this
				await getChatList({
					room_id: this.room_id,
					page: this.page
				}).then(res => {
					that._freshing = false;
					this.temp_list = res.data.chat.data
					// this.chatList = [...res.data.chat.data, ...this.chatList]
					this.total_page = res.data.chat.last_page
					this.last_id = this.temp_list[this.temp_list.length - 1].id

				})
			},
			onrefresh(e) {
				let that = this
				if (that._freshing) return;
				that._freshing = true;
				this.getChat(0)
				// setTimeout(() => {
				// 	that.triggered = false;
				// 	this.chatList = [...this.temp_list, ...this.chatList]
				// 	if (this.page < this.total_page) {
				// 		this.allow_refresh = true
				// 	} else {
				// 		this.allow_refresh = false
				// 	}
				// 	console.log('结束', that.triggered);
				// }, 500)
				// setTimeout(() => {
				// 	if (this.is_init) {
				// 		this.scrollView = 'tab' + this.last_id
				// 	}
				// 	console.log(this.scrollView);
				// }, 800)
			},
			updateUnread() {
				updateUnread({
					room_id: this.room_id
				}).then(res => {
					if (res.code != 0) {
						// uni.$showMsg(res.msg)
						console.log('unread', res.msg);
					}
				})
			},

			toupper(e) {
				console.log(e);
				setTimeout(() => {
					this.scrollView = 'tab' + this.chatList[0].id
					console.log(this.scrollView);
				}, 50)
			},
			tobottom(e) {
				// console.log(e);
				// setTimeout(() => {
				// 	this.scrollView = 'tab' + this.chatList[this.chatList.length - 1].id
				// }, 50)
			},
			onpull(e) {
				// console.log('pull', e);
			},
			onstore(e) {
				this.triggered = 'restore'
				// console.log('onstore', e);
			},
			more() {
				let more = []
				// let lenght = more.length
				// this.$nextTick(() => {
				// 	this.scrollView = 's' + lenght
				// })
				// console.log(this.scrollView);
				this.chatList = [...more, ...this.chatList]
			},
			getHeight() {
				setTimeout(() => {
					let info = uni.createSelectorQuery().select('.chatlength')
					info.boundingClientRect(function(data) { //data - 各种参数
						console.log(data.height);
						uni.pageScrollTo({
							scrollTop: data.height
						})
					}).exec()
				})
			},
			bigImg(url) {
				let base = this.$config.websiteUrl
				let urls = [url]
				uni.previewImage({
					urls: urls
				})
			},
			sendSocketMessage(msg) {
				if (socketOpen) {
					uni.sendSocketMessage({
						data: msg
					});
				}
			},
			confirmSend() {
				let that = this
				if (!this.room_id) {
					return uni.$showMsg('房间不存在')
				}
				// if (!this.is_connect) {
				// 	uni.$showMsg('房间连接失败')
				// 	that.webSocket()
				// 	return false
				// }
				if (this.content == '' || this.content == undefined) {
					uni.$showMsg('请输入内容')
					return false
				}
				if (this.confirm_text != '') {
					uni.showModal({
						title: '温馨提示',
						content: this.confirm_text,
						success(data) {
							if (data.confirm) {
								that.sendMsg()
							}
						}
					})
				} else {
					sendMsg()
				}
			},
			sendMsg() {
				let that = this
				var content = this.content
				this.content = ''
				sendMsg({
					room_id: that.room_id,
					area_id: that.area_id,
					type: 1,
					content: content,
				}).then(res => {
					if (res.code == 0) {
						this.closeEx()
						let data = res.data
						this.chatList.push(data)
						setTimeout(() => {
							that.scrollView = 'tab' + res.data.id
							that.chatLastMsgId = 'tab' + res.data.id
							// that.setPageScrollTo(`#${that.scrollView}`)
							uni.pageScrollTo({
								duration: 100,
								selector: `#${that.scrollView}`,
								success() {
									console.log('滚动成功');
								},
								fail(err) {
									console.log('滚动失败');
								}
							})
						}, 100)
						let sendData = JSON.parse(JSON.stringify(res.data))
						sendData.say_type = 2
						this.socketTask.send({
							data: JSON.stringify({
								type: 1,
								content: sendData,
								room_id: that.room_id
							}),
							success(res) {
								console.log(res);
							},
							fail(err) {
								console.log(err);
							}
						})
						// this.getHeight()
					} else {
						uni.$showMsg(res.msg)
					}
				})

			},
			uploadImg() {
				let that = this
				uni.chooseImage({
					count: 1,
					success: (res) => {
						let imgurl = res.tempFilePaths[0]
						uni.uploadFile({
							//开发者服务器 url
							url: that.$config.requestUrl + '/common/upload',
							method: "POST",
							filePath: imgurl,
							fileType: 'image',
							name: 'UploadFile',
							header: {
								'tokens': uni.getStorageSync('tokens'),
								// 'Content-Type': 'application/x-www-form-urlencoded'  
							},
							formData: {
								accept: 'image',
								room_id: that.room_id
							},
							success: (file) => {
								let info = JSON.parse(file.data)
								if (info.code == 0) {
									sendMsg({
										room_id: that.room_id,
										type: 2,
										file_id: info.data.id,
									}).then(res => {
										if (res.code == 0) {
											let data = res.data
											that.chatList.push(data)
											setTimeout(() => {
												that.scrollView = 'tab' + res.data
													.id
												that.chatLastMsgId = 'tab' + res
													.data.id
												// that.setPageScrollTo(`#${that.scrollView}`)
												uni.pageScrollTo({
													duration: 100,
													selector: `#${that.scrollView}`,
													success() {
														console.log(
															'滚动成功');
													},
													fail(err) {
														console.log(
															'滚动失败');
													}
												})
											}, 100)
											let sendData = JSON.parse(JSON.stringify(res
												.data))
											sendData.say_type = 2
											uni.sendSocketMessage({
												data: JSON.stringify({
													type: 2,
													content: sendData,
													room_id: that.room_id
												}),
												success(res) {
													console.log(res);
												},
												fail(err) {
													console.log(err);
												}
											})
											// this.getHeight()
										} else {
											uni.$showMsg(res.msg)
										}
									})
								} else {
									uni.$showMsg(info.msg)
								}

							}

						})
					}
				})
			}
		}
	}
</script>

<style lang="scss">
	page {
		background: #f7f7f7;
	}

	.ys {
		padding-bottom: 1px;
		box-sizing: border-box;
	}

	.more_text {
		text-align: center;
		margin-bottom: 16px;
		font-size: 12px
	}

	.more {
		text-align: center;
		padding-bottom: 10px;
	}

	.chatscroll {
		// height: calc(100vh - 104px);
		height: auto !important;
		overflow-y: scroll;
		padding-bottom: 50px;

		&::-webkit-scrollbar {
			display: none;
			/* Chrome Safari */
		}
	}

	.sendmsg {
		position: fixed;
		width: 100%;
		background: #fff;
		min-height: 40px;
		bottom: 0;
		/* #ifdef H5 */
		bottom: 0;
		/* #endif */
		padding: 5px 0;
		box-sizing: border-box;
		line-height: 20px;

		.top {
			align-items: flex-end;
			display: flex;
			box-sizing: border-box;
			width: 100%;
			padding: 0 10px;
		}

		.emoji {
			width: 100%;
			background: #fff;
		}

		.textbox {
			width: calc(100% - 40px - 75px);
			position: relative;

			#hiddenText {
				width: 100%;
				position: absolute;
				z-index: -1;
				padding: 8px;
				box-sizing: border-box;
			}
		}

		textarea {
			background: #efefef;
			width: 100%;
			padding: 8px;
			border-radius: 5px;
			max-height: 72px;
			height: auto;
			line-height: 24px;
			box-sizing: border-box;
		}

		textarea:empty {
			overflow: hidden;
		}

		.imgbox {
			height: 40px;
			display: flex;
			align-items: center;
		}

		image {
			width: 30px;
			margin-left: 10px;
			transition: .5;
		}

		.emo {
			image {
				margin-left: 0;
				margin-right: 10px;
			}
		}

		text {
			margin-left: 10px;
			background: #0a9413;
			color: #fff;
			height: 37px;
			width: 65px;
			display: flex;
			justify-content: center;
			align-items: center;
			box-sizing: border-box;
			border-radius: 5px;
			transition: .5;
		}
	}

	.chatlist {
		padding-top: 10px;
	}

	.chatitem {
		padding: 0 10px;
		margin-bottom: 15px;

		.headerimg {
			margin-top: 5px;
			width: 35px;
			height: 35px;
			border-radius: 5px;
			float: left;
		}

		.item-info {
			width: calc(90vw - 55px);
			padding-left: 10px;
			float: left;

			.name {
				color: #777;
				font-size: 12px;
				margin-bottom: 3px;

				text {
					margin-left: 5px;
				}
			}

			.item-msg {
				max-width: 100%;
				font-size: 14px;
				float: left;

				text {
					padding: 8px 12px;
					border-radius: 5px;
					background: #fff;
					display: block;
					line-height: 22px;
				}
			}

			.item-imgbox {
				height: 100%;
				height: 180px;

				image {
					// width: 50%;
					// max-width: 70%;
					height: 100%;
				}
			}
		}
	}

	.chatitem::after {
		content: '';
		display: block;
		height: 0;
		clear: both;
		visibility: hidden;
	}

	.mychat {
		.headerimg {
			float: right;
		}

		.item-info {
			float: right;
			padding-left: 0;
			padding-right: 10px;

			.name {
				text-align: right;
			}

			.item-msg {
				float: right;

				text {
					background: #a0e959;
				}
			}

			.item-imgbox {
				text-align: right;
			}

		}
	}
</style>